//package com.ruoyi.business.service.impl;
//
//import com.alibaba.fastjson.JSONObject;
//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.ruoyi.bizsys.domain.*;
//import com.ruoyi.bizsys.service.*;
//import com.ruoyi.bizsys.dto.PayTrans;
//import com.ruoyi.business.Vo.RulePremiseVo;
//import com.ruoyi.business.common.AsyncService;
//import com.ruoyi.business.common.config.ProtocolConfig;
//import com.ruoyi.business.common.config.TDRuleConfig;
//import com.ruoyi.business.common.riskRule.RulePremiseService;
//import com.ruoyi.business.common.riskRule.RuleStrategy;
//import com.ruoyi.business.domain.*;
//import com.ruoyi.business.mapper.LoanMapper;
//import com.ruoyi.business.service.*;
//import com.ruoyi.common.utils.AwsUtil;
//import com.ruoyi.business.util.Constants;
//import com.ruoyi.business.util.PdfUtils;
//import com.ruoyi.common.config.AwsConfig;
//import com.ruoyi.common.config.RuoYiConfig;
//import com.ruoyi.common.config.ServerYml;
//import com.ruoyi.common.constant.RiskConstants;
//import com.ruoyi.common.constant.UserConstants;
//import com.ruoyi.common.core.redis.RedisCache;
//import com.ruoyi.common.enums.RspEnmu;
//import com.ruoyi.common.enums.UserTagEnum;
//import com.ruoyi.common.exception.BusinessException;
//import com.ruoyi.common.utils.*;
//import com.ruoyi.common.utils.bean.BeanUtils;
//import com.ruoyi.common.utils.file.FileUploadUtils;
//import com.ruoyi.common.utils.file.FileUtils;
//import com.ruoyi.common.utils.uuid.IdUtils;
//import com.ruoyi.extdata.common.config.PayStackConfig;
//import com.ruoyi.extdata.service.IExternalApiService;
//import com.ruoyi.riskrule.RuleEngineService;
//import com.ruoyi.sms.domain.SmsSendData;
//import com.ruoyi.sms.service.ISmsService;
//import com.ruoyi.system.domain.SysFiles;
//import com.ruoyi.system.service.ISysDictDataService;
//import com.ruoyi.system.service.ISysFilesService;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.scheduling.annotation.Async;
//import org.springframework.stereotype.Service;
//import org.springframework.util.CollectionUtils;
//
//import java.io.File;
//import java.io.IOException;
//import java.math.BigDecimal;
//import java.net.URL;
//import java.text.SimpleDateFormat;
//import java.util.Date;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//import java.util.stream.Collectors;
//
//import static com.ruoyi.business.util.Constants.LOAN_STATUS_1o_CANCEL;
//
///**
// * @Author: Jamnsin
// * @Date: 2021/3/10 6:04 下午
// */
//@Slf4j
//@Service
//public class LoanServiceImpl extends BaseService implements ILoanService {
//
//    @Autowired
//    ICreditAccountService creditAccountService;
//
//    @Autowired
//    IProductInfoService productInfoService;
//
//    @Autowired
//    IBLoanInfoService bLoanInfoService;
//
//    @Autowired
//    ILoanOrderService loanOrderService;
//
//    @Autowired
//    IExternalApiService externalApiService;
//
//    @Autowired
//    RuleEngineService ruleEngineService;
//
//    @Autowired
//    IPayTransService payTransService;
//
//    @Autowired
//    LoanMapper loanMapper;
//
//    @Autowired
//    PayStackConfig payStackConfig;
//
//    @Autowired
//    ISysDictDataService sysDictDataService;
//
//    @Autowired
//    ISmsService smsService;
//
//    @Autowired
//    ILoanIouService loanIouService;
//
//    @Autowired
//    IAppService appService;
//
//    @Autowired
//    ProtocolConfig contractConfig;
//
//    @Autowired
//    ISysFilesService sysFilesService;
//
//    @Autowired
//    ICustBankCardService custBankCardService;
//
//    @Autowired
//    RulePremiseService premiseService;
//
//    @Autowired
//    ILoanOrderErrorLogService loanOrderErrorLogService;
//
//    @Autowired
//    private RedisCache redisCache;
//
//    @Autowired
//    ISysDictDataService dictDataService;
//
//    @Autowired
//    AsyncService asyncService;
//
//    @Autowired
//    IAppUserPushService iAppUserPushService;
//
//    @Autowired
//    IBankCodeService bankCodeService;
//
//    @Autowired
//    ICreditAccountInfoService creditAccountInfoService;
//
//    @Autowired
//    ICreditFlagService creditFlagService;
//
//    @Autowired
//    IRealNameAuthService iRealNameAuthService;
//
//    @Autowired
//    ICustomerAndonService customerAndonService;
//
//    @Autowired
//    IAppUserService iAppUserService;
//
//    @Autowired
//    RulePremiseService rulePremiseService;
//
//    @Autowired
//    ICreditFlagService iCreditFlagService;
//
//    @Autowired
//    IIncreasedLimitLogService increasedLimitLogService;
//
//    @Autowired
//    IAppDeviceInfoService appDeviceInfoService;
//
//    @Autowired
//    AwsConfig awsConfig;
//
//    @Override
//    public void processLoanReq(LoanReq loanReq) {
//
//        AppUser appUser = getAppUser();
//        String custNo = getCustNo();
//
//        checkLoan(custNo, loanReq.getLoanSerialNo());
//
//        // 验证是否绑卡
//        //checkIsBindCard(appUser);
//
//        // 逾期不能提现
//        if (isOverdue(custNo)) {
//            throw new BusinessException(RspEnmu.NOT_LOAN_BEFORE_REPAY_OVERDUE_LOAN);
//        }
//
//        // 验证在途件 1, 2，3，6，7, 9
////        if (isLoanApplyOnTheWay(custNo)) {
////            throw new BusinessException(RspEnmu.LOAN_APPLY_IS_ALREADY_ON_THE_WAY);
////        }
//
//        // 是否有Processing，OutStanding的订单
//        if (bLoanInfoService.isLoanInfoListByInTransit(custNo)) {
//            throw new BusinessException(RspEnmu.LOAN_APPLY_IS_ALREADY_ON_THE_WAY);
//        }
//
//        // 验证授信账户是否正常
//        CreditAccount creditAccount = getCreditAccount();
//        //Long creditAccountId = creditAccount.getId();
//
//        if (StringUtils.equals(loanReq.getProductCode(), "0000")) {
//            String productCode = getSuitableProduct();
//            loanReq.setProductCode(productCode);
//        }
//
//        // 查询产品信息
//        ProductInfo product = getProductInfo(loanReq.getProductCode());
//
//        // 提现金额是否在产品额度及可用额度范围内
//        BigDecimal loanAmt = loanReq.getLoanAmt();
//        checkLoanAmt(loanAmt, creditAccount, product, appUser.getUserUuid());
//
//        //设备信息
//        saveAppDevice(appUser.getUserUuid(), custNo, loanReq);
//
//        // 生成提现订单
//        generateLoanOrder(loanReq, product, custNo);
//
//        // 更新账户额度，冻结提现额度
//        updatefrozenQuota(loanAmt, creditAccount);
//
//        RulePremiseVo rulePremiseVo = RulePremiseVo.builder().custNo(getCustNo()).type(RuleStrategy.LOAN).serialNo(loanReq.getLoanSerialNo()).build();
//        JSONObject deviceInfo = loanReq.getDeviceInfo();
//        if (Func.isNotEmpty(deviceInfo) && Func.isNotEmpty(deviceInfo.get("fingerprint"))) {
//            rulePremiseVo.setFingerprint(deviceInfo.getString("fingerprint"));
//        }
//        premiseService.rulePremise(rulePremiseVo, "orderFlag", "deviceFlag");
//    }
//
//    @Override
//    public void processLoanReqV228(LoanReq loanReq) {
//
//        AppUser appUser = getAppUser();
//        String custNo = getCustNo();
//
//        checkLoan(custNo, loanReq.getLoanSerialNo());
//
//        // 验证是否绑卡
//        //checkIsBindCard(appUser);
//
//        // 逾期不能提现
//        if (isOverdue(custNo)) {
//            throw new BusinessException(RspEnmu.NOT_LOAN_BEFORE_REPAY_OVERDUE_LOAN);
//        }
//
//        // 验证在途件 1, 2，3，6，7, 9
////        if (isLoanApplyOnTheWay(custNo)) {
////            throw new BusinessException(RspEnmu.LOAN_APPLY_IS_ALREADY_ON_THE_WAY);
////        }
//
//        // 是否有Processing，OutStanding的订单
//        if (bLoanInfoService.isLoanInfoListByInTransit(custNo)) {
//            throw new BusinessException(RspEnmu.LOAN_APPLY_IS_ALREADY_ON_THE_WAY);
//        }
//
//        // 验证授信账户是否正常
//        CreditAccount creditAccount = getCreditAccount();
//        //Long creditAccountId = creditAccount.getId();
//
//        if (StringUtils.equals(loanReq.getProductCode(), "0000")) {
//            String productCode = getSuitableProduct();
//            loanReq.setProductCode(productCode);
//        }
//
//        // 查询产品信息
//        ProductInfo product = getProductInfo(loanReq.getProductCode());
//
//        // 提现金额是否在产品额度及可用额度范围内
//        BigDecimal loanAmt = loanReq.getLoanAmt();
//        checkLoanAmt(loanAmt, creditAccount, product, appUser.getUserUuid());
//
//        //设备信息
//        saveAppDevice(appUser.getUserUuid(), custNo, loanReq);
//
//        // 生成提现订单
//        generateLoanOrder(loanReq, product, custNo);
//
//        // 更新账户额度，冻结提现额度
//        updatefrozenQuota(loanAmt, creditAccount);
//
//        RulePremiseVo rulePremiseVo = RulePremiseVo.builder().custNo(getCustNo()).type(RuleStrategy.LOAN).serialNo(loanReq.getLoanSerialNo()).userId(appUser.getUserUuid()).build();
//        JSONObject deviceInfo = loanReq.getDeviceInfo();
//        if (Func.isNotEmpty(deviceInfo) && Func.isNotEmpty(deviceInfo.get("newFingerprint"))) {
//            rulePremiseVo.setFingerprint(deviceInfo.getString("newFingerprint"));
//        }
//        premiseService.rulePremiseV228(rulePremiseVo);
//    }
//
//    private void saveAppDevice(String userId, String custNo, LoanReq loanReq) {
//        appService.saveAppDeviceInfo(userId, custNo, Constants.ACTION_TYPE_LOAN, loanReq.getLoanSerialNo(), loanReq.getDeviceInfo());
//    }
//
//    private boolean isOverdue(String custNo) {
//        LoanIou loanIou = new LoanIou();
//        loanIou.setCustNo(custNo);
//        loanIou.setState(Constants.BIZ_STATUS_1);
//        List<LoanIou> loanIouList = loanIouService.selectLoanIouList(loanIou);
//        boolean isOverdue = loanIouList.stream().anyMatch(p -> p.getIouStatus() == 2);
//        return isOverdue;
//    }
//
//    //前置校验通过 调用规则引擎
//    @Override
//    public void rulePass(String applySerialNo) {
//
//
//        LoanOrder loanOrderQ = new LoanOrder();
//        loanOrderQ.setLoanSerialNo(applySerialNo);
//        loanOrderQ.setLoanStatus(Constants.LOAN_STATUS_9_APPROVALING);
//
//        List<LoanOrder> loanOrders = loanOrderService.selectLoanOrderList(loanOrderQ);
//        if (loanOrders.size() == 0) {
//            throw new BusinessException(RspEnmu.LOAN_APPLY_NOT_EXISTS);
//        }
//        LoanOrder loanOrder = loanOrders.get(0);
//
//        AppUser appUser = getAppUserByCustNo(loanOrder.getCustNo());
//        if (appUser == null) {
//            throw new BusinessException(RspEnmu.USERID_IS_EMPTY);
//        }
//
//        CreditAccount creditAccount = getCreditAccount(loanOrder.getCustNo());
//
//        try {
//            // 推送信息到规则引擎
//            JSONObject ruleRst = ruleEngineService.riskRuleEngine(RiskConstants.RULE_TYPE_LOAN, loanOrder.getLoanSerialNo());
//
//            //中断
//            String approveFlag = ruleRst.getString(RiskConstants.RULE_RESULT_DEAL_TYPE_KEY);
//            if (StringUtils.equals(approveFlag, RiskConstants.RULE_RESULT_REVOKE)) {
//                throw new BusinessException(RspEnmu.OTP_REQUEST);
//            }
//
//            handleLoan(loanOrder, creditAccount, appUser, ruleRst, approveFlag);
//        } catch (Exception e) {
//            // 提现订单状态为2 的不做处理
//            if (loanOrder.getLoanStatus() != Constants.LOAN_STATUS_2_INSUFFICIENT_ACCOUNT_BALANCE) {
//                asyncService.apdUserTag(AppUserMark.builder().userId(appUser.getUserUuid()).secondTag(e.getMessage()).build(), UserTagEnum.getDiy("Withdrawal failed", e.getMessage()));
//            }
//            log.info("提现异常抛出：{}", e);
//        }
//
//    }
//
//    public void handleLoan(LoanOrder loanOrder, CreditAccount creditAccount, AppUser appUser, JSONObject ruleRst, String approveFlag) {
//        //锁住订单再操作
//        String lockKey = Constants.LOAN_LOCK_KEY_PREFIX + loanOrder.getLoanSerialNo();
//
//        int j = 0;//重试次数
//        while (j < Constants.CUST_ACCOUNT_LOCK_REGET_COUNT) {//重试次数内
//            j++;
//            log.info("Loan 流水号 {} 第 {} 次获取锁", loanOrder.getLoanSerialNo(), j);
//            String lockValue = IdUtils.simpleUUID();
//            boolean lock = redisCache.lock(lockKey, lockValue);//获取锁
//
//            if (lock) {
//                try {
//                    long start = System.currentTimeMillis();
//
//                    //重新查询loanOrder
//                    loanOrder = loanOrderService.getById(loanOrder.getId());
//
//                    if (loanOrder.getLoanStatus() != Constants.LOAN_STATUS_9_APPROVALING) {
//                        break;
//                    }
//
//                    //保存风控需要的字段到客户信息表
//                    creditAccountInfoService.updateCustomerByRuleResult(ruleRst, creditAccount.getCustNo());
//
//                    //接收审批结果，修改审批状态为拒绝，解冻提现额度
//                    if (StringUtils.equals(approveFlag, RiskConstants.RULE_RESULT_REJECT)) {
//                        loanOrder.setFreezeDate(ruleRst.getString(RiskConstants.RULE_RESULT_LOAN_FREEZE));
//                        updateFrozenAndLoanStatus(loanOrder, creditAccount.getId(), Constants.LOAN_STATUS_0_APPROVE_REFUSED, "rule reject");
//                        //提现拒绝
//                        asyncService.apdUserTag(AppUserMark.builder().userId(appUser.getUserUuid()).build(), UserTagEnum.LOAN_REJECT);
//                        return;
//                    }
//
//                    RealNameAuth auth = new RealNameAuth();
//                    auth.setUserId(appUser.getUserUuid());
//                    auth.setState(Constants.BIZ_STATUS_1);
//                    List<RealNameAuth> realNameAuthList = realNameAuthService.selectRealNameAuthList(auth);
//
//                    //关闭
//                    if (StringUtils.equals(approveFlag, RiskConstants.RULE_RESULT_CLOSE)) {
//                        updateFrozenAndLoanStatus(loanOrder, creditAccount.getId(), Constants.LOAN_STATUS_8_CLOSE, ruleRst.getString(RiskConstants.RULE_RESULT_CLOSE_REASON));
//                        //发送短信
//                        JSONObject smsParam = new JSONObject();
//                        smsParam.put("lastName", realNameAuthList.get(0).getLastName());
//                        SmsSendData smsData = SmsSendData.builder().noticeType(Constants.SMS_NOTICE_TYPE_NOTICE).smsType(Constants.SMS_TYPE_CUSTRVWRESULT_CLOSE).countryCode(appUser.getCountryCode()).phoneNumber(realNameAuthList.get(0).getPhoneNumber()).smsParam(smsParam).build();
//                        smsService.sendSms(smsData);
//
//                        asyncService.apdUserTag(AppUserMark.builder().userId(appUser.getUserUuid()).build(), UserTagEnum.LOAN_FAILED_WITHDRAWAL_CANCEL);
//                        return;
//                        //throw new BusinessException(RspEnmu.CREDIT_APPLY_REFUSED);
//                    }
//
//                    // 审批通过  OrderStatue = 1
//                    updateLoanOrderStatus(loanOrder.getId(), Constants.LOAN_STATUS_1_APPROVE_PASSED, "rule pass");
//
//                    // 查询资金是否满足，不满足，更新提现状态，并提示付款失败  超时重试三次
//                    Long loanOrderId = loanOrder.getId();
//                    BigDecimal loanAmt = loanOrder.getLoanAmt();
//                    payTransService.tryFunc(e -> checkPayAccountBalance(loanOrderId, creditAccount, loanAmt, appUser));
//
//                    // 生成贷款合同
//                    if (StringUtils.isBlank(loanOrder.getContractNo())) {
//                        String contractNo = IdUtils.generateContractNo();
//                        createContractPdf(contractNo, loanOrder);
//                        //状态：OrderStatue = 7 合同未生成
//                        updateLoanContract(loanOrder.getId(), contractNo);
//                    }
//
//                    transferProcess(loanOrder, appUser, creditAccount);
//
//                    long end = System.currentTimeMillis();
//                    log.info("锁占用时间，耗时：" + (end - start) + " ms");
//                    //无需重试
//                    break;
//                } catch (Exception e) {
//                    //发送飞书 抛出异常
//                    log.error("更新账户信息异常", e);
//                    String className = this.getClass().getName();
//                    String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
//                    FeishuUtils.sendFeishuToMonit(className + "." + methodName, "提现", loanOrder.getCustNo(), loanOrder.getCustNo(), e);
//                    throw new BusinessException("更新账户信息异常");
//                } finally {
//                    //释放锁
//                    redisCache.unLock(lockKey, lockValue);
//                }
//            } else {
//                log.info("Loan 流水号 {} 第 {} 次获取锁失败", loanOrder.getLoanSerialNo(), j);
//
//                try {
//                    Thread.sleep(Constants.CUST_ACCOUNT_LOCK_SLEEP_TIME);
//                } catch (InterruptedException e) {
//                    log.error("Loan 线程 sleep 异常", e);
//                }
//            }
//        }
//    }
//
//    /**
//     * 提现成功流程、定时任务重试
//     *
//     * @param loanOrder
//     * @param appUser
//     * @param creditAccount
//     */
//    @Override
//    public void transferProcess(LoanOrder loanOrder, AppUser appUser, CreditAccount creditAccount) {
//        log.info("transferProcess,入参loanOrder{},AppUser:{},CreditAccount:{}", loanOrder, appUser, creditAccount);
//        //当前创建的流水号不存在则走放款接口流程。   如果存在 需要再校验放款状态 状态未查得 才走接口流程
//        boolean transSerialIsActive;
//        if (StringUtils.isBlank(loanOrder.getPayTransSerialNo())) {
//            String payTransSerialNo = IdUtils.reqId();
//            loanOrder.setPayTransSerialNo(payTransSerialNo);
//            updatePayTransSerialNo(loanOrder.getId(), payTransSerialNo);
//            transSerialIsActive = false;
//        } else {
//            // 查询代付结果
//            //isReTryTask=false 且 接口返回 放款流水号已存在时。该方法会返回false，执行后续接口
//            transSerialIsActive = verifyPayTrans(appUser, creditAccount.getId(), loanOrder, true);
//        }
//
//        //流水号未成效 -> 放款接口流程。  流水号已生效 - > 查询放款状态
//        if (!transSerialIsActive) {
//            LoanReq loanReq = new LoanReq();
//            loanReq.setAccountNumber(loanOrder.getAccountNumber());
//            BankCode bankCode = bLoanInfoService.getBanckInfoByAccountNumber(loanOrder.getAccountNumber());
//            loanReq.setBankCode(bankCode.getPaystackBankCode());
//            loanReq.setLoanAmt(loanOrder.getLoanAmt());
//
//            payTrans(loanReq, appUser, creditAccount.getId(), loanOrder);
//            updateLoanOrderStatus(loanOrder.getId(), Constants.LOAN_STATUS_3_LOAN_PENDING, "loan pending");
//            verifyPayTrans(appUser, creditAccount.getId(), loanOrder, false);
//        }
//
//    }
//
//
//    @Override
//    public boolean verifyPayTrans(AppUser appUser, Long creditAccountId, LoanOrder loanOrder, boolean isRetryTask) {
//        Long loanOrderId = loanOrder.getId();
//        String payTransSerialNo = loanOrder.getPayTransSerialNo();
//
//        JSONObject verifyTransRes = null;
//        try {
//            verifyTransRes = verifyTransfer(payTransSerialNo);
//        } catch (BusinessException e) {
//            //定时任务 放款流水号不存在时 返回false 调用后续接口;  接口报错不修改订单状态
//            if (isRetryTask) {
//                if (RspEnmu.TRANSACTION_SERIAL_NO_NOT_EXISTS.getRetCode().equals(e.getCode())) {
//                    return false;
//                }
//                throw new BusinessException(RspEnmu.VERIFY_TRANSFER_NETWORK_ERROR);
//            }
//
//            if (RspEnmu.TRANSACTION_SERIAL_NO_NOT_EXISTS.getRetCode().equals(e.getCode())) {
//                updateFrozenAndLoanStatus(loanOrder, creditAccountId, Constants.LOAN_STATUS_5_LOAN_FAILED, e.getDetails());
//                throw e;
//            }
//            updateLoanOrderStatus(loanOrderId, Constants.LOAN_STATUS_3_LOAN_PENDING, e.getDetails());
//            throw new BusinessException(RspEnmu.LOAN_FAILED);
//        }
//
//        // 接收代付结果，代付失败，查询是否重新代付开关，无需则修改提现状态为放款失败，需则另行重新触发
//        String transStatus = verifyTransRes.getString("status");
//        if (transStatus.equals("pending")) {
//            updateLoanOrderStatus(loanOrderId, Constants.LOAN_STATUS_3_LOAN_PENDING, "loan pending");
////            throw new BusinessException(RspEnmu.LOAN_PENDING);
//            return true;
//        } else if (transStatus.equals("failed")) {
//            dealFailedLoan(appUser, creditAccountId, loanOrder);
//            //用户标签-提现失败
////            throw new BusinessException(RspEnmu.LOAN_FAILED, verifyTransRes.getString("failures"));
//            return true;
//        } else if (transStatus.equals("otp")) {
//            updateLoanOrderStatus(loanOrderId, Constants.LOAN_STATUS_3_LOAN_PENDING, "need otp");
////            throw new BusinessException(RspEnmu.OTP_REQUEST);
//            return true;
//        }
//        dealSuccessLoan(appUser, creditAccountId, loanOrder);
//        return true;
//    }
//
//    @Override
//    public void processLoanReqAgain(LoanOrder loanOrder) {
//        //跳过非审批中的代码
//        if (Constants.LOAN_STATUS_9_APPROVALING != loanOrder.getLoanStatus()) {
//            throw new BusinessException(RspEnmu.LOAN_STATUS_IS_NOT_APPROVAL);
//        }
//        this.rulePass(loanOrder.getLoanSerialNo());
//    }
//
//    private void checkIsBindCard(AppUser appUser) {
//        if (CollectionUtils.isEmpty(getBindCards(appUser.getUserUuid()))) {
//            throw new BusinessException(RspEnmu.BEFORE_LOAN_NEED_BIND_CARD);
//        }
//    }
//
//    private boolean isBindCard(String userId) {
//        return CollectionUtils.isEmpty(getBindCards(userId)) ? false : true;
//    }
//
//    private List<CustBankCard> getBindCards(String userId) {
//        CustBankCard custBankCard = new CustBankCard();
//        custBankCard.setUserId(userId);
//        custBankCard.setState(Constants.BIZ_STATUS_1);
//        return custBankCardService.selectCustBankCardList(custBankCard);
//    }
//
//    private void checkLoan(String custNo, String loanSerialNo) {
//        //重复序列
//        LoanOrder order = new LoanOrder();
//        order.setLoanSerialNo(loanSerialNo);
//        order.setState(Constants.BIZ_STATUS_1);
//        if (!CollectionUtils.isEmpty(loanOrderService.selectLoanOrderList(order))) {
//            throw new BusinessException(RspEnmu.SERIAL_NO_DUPLICATE);
//        }
//
//        //提现风控拒绝7天惩罚期，7天内不能提现
//        LoanOrder order1 = new LoanOrder();
//        order1.setCustNo(custNo);
//        order1.setState(Constants.BIZ_STATUS_1);
//        //初次提交 更新召回任务-提交提现
//        List<LoanOrder> loanOrderList = loanOrderService.selectLoanOrderList(order1);
//
//        if (loanOrderList.size() > 0 && loanOrderList.get(0).getLoanStatus() == Constants.LOAN_STATUS_0_APPROVE_REFUSED) {
//            LoanOrder loanOrder = loanOrderList.get(0);
//            String freezeDate = loanOrder.getFreezeDate();
//            int freezeDay = 7;
//            if (freezeDate != null) {
//                freezeDay = Integer.valueOf(freezeDate);
//            }
//            if (Func.dayDifference(loanOrder.getCreateTime()) < freezeDay) {
//                Map<Object, Object> hashMap = new HashMap<>();
//                hashMap.put("freezeDay", freezeDate);
//                throw new BusinessException(RspEnmu.NOT_LOAN_WITHIN_7.getRetMsg(), hashMap);
//            }
//        }
//
//        //当日提现失败3次，不能再发起提现
//        LoanOrder order2 = new LoanOrder();
//        order2.setCustNo(custNo);
//        order2.setLoanStatus(Constants.LOAN_STATUS_5_LOAN_FAILED);
//
//        List<LoanOrder> failedOrdes = loanMapper.todayList(custNo, Constants.LOAN_STATUS_5_LOAN_FAILED);
//        List<LoanOrder> failedOrdes1 = loanMapper.todayList(custNo, Constants.LOAN_STATUS_8_CLOSE);
//
//        if (failedOrdes.size() + failedOrdes1.size() > 2) {
//            throw new BusinessException(RspEnmu.REACHED_UPPER_LIMIT);
//        }
//    }
//
//
//    @Override
//    public void dealFailedLoan(AppUser appUser, Long creditAccountId, LoanOrder loanOrder) {
//        Long loanOrderId = loanOrder.getId();
//        BigDecimal loanAmt = loanOrder.getLoanAmt();
//        if (isReInitiatePay()) {
//            updateLoanOrderStatus(loanOrderId, Constants.LOAN_STATUS_6_RE_INITIATE_PAY, "re-initiate pay");
//            return;
//        }
//        updateFrozenAndLoanStatus(loanOrder, creditAccountId, Constants.LOAN_STATUS_5_LOAN_FAILED, "loan failure");
//        sendNotice(appUser, null, Constants.SMS_TYPE_LOAN_FAILED);
//    }
//
//
//    @Override
//    public void saveLoanErrorLog(LoanReq loanReq, Exception e) {
//
//        LoanOrderErrorLog loanOrderErrorLog = new LoanOrderErrorLog();
//        loanOrderErrorLog.setAccountNumber(loanReq.getAccountNumber());
//        loanOrderErrorLog.setCustNo(getCustNo());
//        loanOrderErrorLog.setProductCode(loanReq.getProductCode());
//        loanOrderErrorLog.setLoanAmt(loanReq.getLoanAmt());
//        loanOrderErrorLog.setLoanPurpose(loanReq.getLoanPurpose());
//        loanOrderErrorLog.setLoanPurposeOther(loanReq.getLoanPurposeOther());
//        loanOrderErrorLog.setLoanSerialNo(loanReq.getLoanSerialNo());
//        loanOrderErrorLog.setCreateTime(new Date());
//
//        loanOrderErrorLog.setErrMsg(e.getMessage());
//        if (e instanceof BusinessException) {
//            BusinessException businessException = (BusinessException) e;
//            loanOrderErrorLog.setErrCode(businessException.getCode() == null ? null : Long.valueOf(businessException.getCode()));
//            loanOrderErrorLog.setErrDetail(businessException.getDetails());
//        }
//        loanOrderErrorLogService.insertLoanOrderErrorLog(loanOrderErrorLog);
//    }
//
//    @Override
//    public void dealSuccessLoan(AppUser appUser, Long creditAccountId, LoanOrder loanOrder) {
//
//        //更新合同 非当日则重新创建合同
//        if (DateUtils.daysBetween(loanOrder.getCreateTime(), new Date()) > 0) {
//            String contractNo = IdUtils.generateContractNo();
//            createContractPdf(contractNo, loanOrder);
//            loanOrder.setContractNo(contractNo);
//        }
//
//        // 解冻并减少提现金额
//        updateFrozenAndLoanStatus(loanOrder, creditAccountId, Constants.LOAN_STATUS_4_LOAN_SUCCESS, "loan success");
//
//        // 生成借据
//        generateLoanIou(loanOrder);
//
//        //更新账户汇总信息
//        CreditAccount account = creditAccountService.selectCreditAccountById(creditAccountId);
//        bLoanInfoService.updateAccount(account);
//
//        // 短信通知
//        sendNotice(appUser, loanOrder, Constants.SMS_TYPE_LOAN_SUCCESS);
//
//        //通知app
//        AppUserPush appUserPush = new AppUserPush();
//        appUserPush.setUserId(appUser.getUserUuid());
//        appUserPush.setPushType(Constants.PUSH_TYPE_SCORE);
//        List<AppUserPush> appUserPushes = iAppUserPushService.selectAppUserPushList(appUserPush);
//        if (appUserPushes.size() == 0) {
//            iAppUserPushService.insertAppUserPush(appUserPush);
//        }
//
//        //用户标签-提现成功
//        IncreasedLimitLog increasedAmtByCust = increasedLimitLogService.getIncreasedAmtByCust(account.getCustNo());
//        AppUserMark appUserMark = AppUserMark.builder().userId(appUser.getUserUuid())
//                .creditLine(account.getCreditLine()).loanQuota(account.getLoanQuota()).increasedAmt(increasedAmtByCust.getIncreasedAmt()).build();
//        int cardCount = custBankCardService.count(new QueryWrapper<CustBankCard>().eq("cust_no", account.getCustNo()));
//        asyncService.apdUserTag(appUserMark, cardCount > 0 ? UserTagEnum.LOAN_SUCCEED_BIND_CARD : UserTagEnum.LOAN_SUCCEED_NOT_CARD);
//    }
//
//    @Override
//    public CustAccount getCustAccount() {
//        String userId = getUserId();
//        return loanMapper.getCustAccount(userId);
//    }
//
//    @Override
//    public List<CustLoanIou> getCustNotSettledIou() {
//        return loanMapper.getCustNotSettledIou();
//    }
//
//    private void payTrans(LoanReq loanReq, AppUser appUser, Long creditAccountId, LoanOrder loanOrder) {
//
//        String payTransSerialNo = loanOrder.getPayTransSerialNo();
//        try {
//            PayTrans payTrans = PayTrans.builder().accountNumber(loanReq.getAccountNumber()).bankCode(loanReq.getBankCode()).loanAmt(loanReq.getLoanAmt()).payTransSerialNo(payTransSerialNo).userId(appUser.getUserUuid()).build();
//            payTransService.payTrans(payTrans);
//        } catch (Exception e) {
//            log.error("代付交易处理异常，", e);
//
//            if (e instanceof BusinessException) {
//                BusinessException be = (BusinessException) e;
//                //放款号已存在 不改变订单状态
//                if (RspEnmu.REFERENCE_ALREADY_EXISTS_ON_TRANSFER.getRetMsg().equals(be.getMessage())) {
//                    throw e;
//                }
//                //return false 如果不是超时和异常 那么均是失败
//                if (!RspEnmu.NETWORK_BUSY.getRetCode().equals(be.getCode())) {
//                    updateFrozenAndLoanStatus(loanOrder, creditAccountId, Constants.LOAN_STATUS_5_LOAN_FAILED, e.getMessage());
//                    //sendNotice(appUser, null, Constants.SMS_TYPE_BALANCE_INSUFFICIENT);
//                }
//            }
//            throw e;
//        }
//    }
//
//    private void updateLoanContract(Long loanOrderId, String contractNo) {
//        LoanOrder loanOrder = new LoanOrder();
//        loanOrder.setId(loanOrderId);
//        loanOrder.setContractNo(contractNo);
//        loanOrder.setLoanStatus(Constants.LOAN_STATUS_7_CONTRAC_NO_GENERATED);
//        loanOrderService.updateLoanOrder(loanOrder);
//    }
//
//    @Override
//    public void createContractPdf(String contractNo, LoanOrder loanOrder) {
//
//        String tmpPath = RuoYiConfig.getUploadPath() + "/tmp";
//        String contractPath = RuoYiConfig.getUploadPath() + "/contract";
//        File contractFilePath = new File(contractPath);
//        if (!new File(tmpPath).exists()) {
//            new File(tmpPath).mkdirs();
//        }
//        if (!contractFilePath.exists()) {
//            contractFilePath.mkdirs();
//        }
//
//        log.debug("contractFile：{}", contractPath);
//
//        Map<String, String> map = buildPdfParam(contractNo, loanOrder);
//
//        String contractTmpFilePath = tmpPath + File.separator + contractNo + ".pdf";
//        PdfUtils.createPDF(map, contractConfig.getLoanContractTemplate(), contractTmpFilePath);
//        File contractTmpFile = new File(contractTmpFilePath);
//        if (!contractTmpFile.exists()) {
//            log.info("合同生成失败");
//            throw new BusinessException(RspEnmu.CONTRAC_GENERATE_ERR);
//        }
//        try {
//            if (("PRO").equals(ServerYml.getRunEnv())) {
//                log.info("ServerYml.getRunEnv()):" + ServerYml.getRunEnv());
//                //上传到AWS对象桶
//                log.info("contractTmpFile:" + contractTmpFile.getPath());
//                //获取当前时间
//                Date date = new Date();
//                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
//                String key = awsConfig.getPdfPath() + dateFormat.format(date);
//                log.info("key:" + key);
//                URL url = AwsUtil.uploadObject(awsConfig.getBucketName(), key + "/" + contractTmpFile.getName(), contractTmpFile.getPath());
//                //上传至本地
//                //String fileName = FileUploadUtils.upload(contractPath, FileUtils.fileToMultipartFile(contractTmpFile));
//                log.debug("合同地址：{}", url);
//
//                SysFiles sysFile = new SysFiles();
//                sysFile.setMediaId(contractNo);
//                //sysFile.setUrl(fileName);
//                sysFile.setAwsS3Url(String.valueOf(url));
//                sysFilesService.insertSysFiles(sysFile);
//            } else {
//                log.info("ServerYml.getRunEnv()):" + ServerYml.getRunEnv());
//                String fileName = FileUploadUtils.upload(contractPath, FileUtils.fileToMultipartFile(contractTmpFile));
//                log.debug("合同地址：{}", fileName);
//
//                SysFiles sysFile = new SysFiles();
//                sysFile.setMediaId(contractNo);
//                sysFile.setUrl(fileName);
//                sysFilesService.insertSysFiles(sysFile);
//            }
//
//        } catch (IOException e) {
//            log.error("合同上传异常", e);
//            throw new BusinessException(RspEnmu.CONTRAC_GENERATE_ERR);
//        }
//
//        try {
//            if (contractTmpFile.exists()) {
//                contractTmpFile.delete();
//            }
//        } catch (Exception e) {
//            log.error("删除合同临时文件异常，{}", e.getMessage());
//        }
//
//    }
//
//    private Map<String, String> buildPdfParam(String contractNo, LoanOrder loanOrder) {
//        RealNameAuth realNameAuth = getRealNameByCustNo(loanOrder.getCustNo());
//
//        Map<String, String> map = new HashMap<>();
//        map.put("contractNo", contractNo);
//        map.put("firstName", realNameAuth.getFirstName());
//        map.put("middleName", realNameAuth.getMiddleName());
//        map.put("lastName", realNameAuth.getLastName());
//        map.put("birthDate", realNameAuth.getBirthDate());
//        map.put("accountNumber", loanOrder.getAccountNumber());
//        map.put("loanAmount", loanOrder.getLoanAmt().toString());
//        map.put("interestFee", loanOrder.getInterestAmt().toString());
//        map.put("serviceFee", loanOrder.getServiceFee().toString());
//        map.put("repaymentDate", loanOrder.getRepayDate());
//
//        return map;
//    }
//
//    private String getSuitableProduct() {
//        return loanMapper.getSuitableProduct();
//    }
//
//    private void checkLoanAmt(BigDecimal loanAmt, CreditAccount creditAccount, ProductInfo product, String userId) {
//        BigDecimal minQuota = product.getMinQuota();
//        BigDecimal maxQuota = product.getMaxQuota();
//        BigDecimal creditScale = product.getCreditScale();
//        BigDecimal productCreditQuota = creditAccount.getCreditLine().multiply(creditScale);
//        BigDecimal availableQuota = loanMapper.getAvailableQuota(creditAccount.getCustNo());
//
//        log.info("loanAmt = {}, minQuota = {}, maxQuota = {}, creditScale = {}, productCreditQuota = {}, availableQuota = {}", loanAmt, minQuota, maxQuota, creditScale, productCreditQuota, availableQuota);
//
//        if (loanAmt.doubleValue() <= 0 || loanAmt.doubleValue() < minQuota.doubleValue()) {
//            throw new BusinessException(RspEnmu.LOWER_THAN_PRODUCT_MIN_QUOTA);
//        }
//
//        if (loanAmt.doubleValue() > productCreditQuota.doubleValue() || loanAmt.doubleValue() > maxQuota.doubleValue()) {
//            throw new BusinessException(RspEnmu.MORE_THAN_PRODUCT_QUOTA);
//        }
//
//        if (loanAmt.doubleValue() > availableQuota.doubleValue()) {
//            throw new BusinessException(RspEnmu.CREDIT_LINE_AVAILABLE_QUOTA_INSUFFICIENT);
//        }
//
//        if (!isBindCard(userId)) {
//            BigDecimal loanQuotaRatio = BigDecimal.valueOf(Double.valueOf(dictDataService.selectDictLabel("loan_settings", "loan_quota_ratio")));
//            BigDecimal withdrawalLimit = creditAccount.getCreditLine().multiply(loanQuotaRatio).subtract(creditAccount.getLoanQuota()).subtract(creditAccount.getFrozenQuota());
//            withdrawalLimit = withdrawalLimit.doubleValue() < 0 ? BigDecimal.ZERO : withdrawalLimit;
//            log.info("loanQuotaRatio = {}, withdrawalLimit = {}", loanQuotaRatio, withdrawalLimit);
//            if (loanAmt.doubleValue() > withdrawalLimit.doubleValue()) {
//                throw new BusinessException(RspEnmu.CREDIT_LINE_AVAILABLE_QUOTA_INSUFFICIENT);
//            }
//        }
//
//        LoanIou loanIou = new LoanIou();
//        loanIou.setCustNo(creditAccount.getCustNo());
//        loanIou.setState(Constants.BIZ_STATUS_1);
//        List<LoanIou> loanIouList = loanIouService.selectLoanIouList(loanIou);
//        if (!CollectionUtils.isEmpty(loanIouList)) {
//            List<LoanIou> noSettleLoanIous = loanIouList.stream().filter(p -> p.getIouStatus() != 1).collect(Collectors.toList());
//            BigDecimal onlineQuota = noSettleLoanIous.stream().map(LoanIou::getLoanPrincipal).reduce(BigDecimal.ZERO, BigDecimal::add);
//            BigDecimal totalOnlineQuota = onlineQuota.add(creditAccount.getFrozenQuota());
//            onlineQuota = onlineQuota.doubleValue() < 0 ? BigDecimal.ZERO : onlineQuota;
//            totalOnlineQuota = totalOnlineQuota.doubleValue() < 0 ? BigDecimal.ZERO : totalOnlineQuota;
//            BigDecimal dbAvailableQuota = creditAccount.getCreditLine().subtract(totalOnlineQuota);
//            availableQuota = availableQuota.doubleValue() < 0 ? BigDecimal.ZERO : availableQuota;
//            if (onlineQuota.doubleValue() == 0 && totalOnlineQuota.doubleValue() == 0) {
//
//            }
//
//            if (loanAmt.doubleValue() > dbAvailableQuota.doubleValue() || creditAccount.getCreditLine().doubleValue() < totalOnlineQuota.doubleValue()) {
//                throw new BusinessException(RspEnmu.CREDIT_LINE_AVAILABLE_QUOTA_INSUFFICIENT);
//            }
//        }
//    }
//
//    public void generateLoanIou(LoanOrder loanOrder) {
//        LoanIou loanIou = new LoanIou();
//        BeanUtils.copyProperties(loanOrder, loanIou);
//        loanIou.setLoanPrincipal(loanOrder.getLoanAmt());
//        loanIou.setLoanInterest(loanOrder.getInterestAmt());
//        loanIou.setIouStatus(Constants.LOAN_IOU_STATUS_WAIT);
//        loanIou.setRepayDate(DateUtils.getFewDay(loanOrder.getPeriodNum()));
//        loanIou.setRemark(null);
//        loanIouService.insertLoanIou(loanIou);
//    }
//
//    private void updateLoanOrderStatus(Long loanOrderId, int loanStatus, String msg) {
//        LoanOrder order = new LoanOrder();
//        order.setId(loanOrderId);
//        order.setLoanStatus(loanStatus);
//        if (StringUtils.isNotBlank(msg)) {
//            order.setRemark(msg);
//        }
//        loanOrderService.updateLoanOrder(order);
//    }
//
//    private void updatePayTransSerialNo(Long loanOrderId, String payTransSerialNo) {
//        LoanOrder order = new LoanOrder();
//        order.setId(loanOrderId);
//        order.setPayTransSerialNo(payTransSerialNo);
//        loanOrderService.updateLoanOrder(order);
//    }
//
//    private void updatefrozenQuota(BigDecimal loanAmt, CreditAccount creditAccount) {
//
//
//        //锁住客户账户再操作
//        String lockKey = Constants.CUST_ACCOUNT_LOCK_KEY_PREFIX + creditAccount.getCustNo();
//
//        int j = 0;//重试次数
//        while (j < Constants.CUST_ACCOUNT_LOCK_REGET_COUNT) {//重试次数内
//            j++;
//            log.info("Repayment 客户号 {} 第 {} 次获取账户锁", creditAccount.getCustNo(), j);
//            String lockValue = IdUtils.fastSimpleUUID();
//            boolean lock = redisCache.lock(lockKey, lockValue);//获取锁
//
//            if (lock) {
//                try {
//                    long start = System.currentTimeMillis();
//                    CreditAccount ca2 = new CreditAccount();
//                    ca2.setId(creditAccount.getId());
//                    ca2.setFrozenQuota(loanAmt);
//                    loanMapper.updatefrozenQuota(ca2);
//                    //无需重试
//                    long end = System.currentTimeMillis();
//                    log.info("锁占用时间，耗时：" + (end - start) + " ms");
//                    break;
//                } finally {
//                    //释放锁
//                    redisCache.unLock(lockKey, lockValue);
//                }
//            } else {
//                log.info("Repayment 客户号 {} 第 {} 次获取账户锁失败", creditAccount.getCustNo(), j);
//
//                try {
//                    Thread.sleep(Constants.CUST_ACCOUNT_LOCK_SLEEP_TIME);
//                } catch (InterruptedException e) {
//                    log.error("Repayment 线程 sleep 异常", e);
//                }
//            }
//        }
//    }
//
//    @Async("threadPoolTaskExecutor")
//    public void sendNotice(AppUser appUser, LoanOrder loanOrder, String smsType) {
//        log.info("准备发送短信");
//        RealNameAuth realNameAuth = getRealNameAuth(appUser.getUserUuid());
//
//        JSONObject smsParam = new JSONObject();
//        switch (smsType) {
//            case Constants.SMS_TYPE_LOAN_SUCCESS:
//                // Dear #lastName#, your loan on LinkCredit have been issued. You will receive N#loanAmt# in your #bankName# account(#cardLast4#). Repay the loans on time and maintaining good credit will help raise your limit.
//                smsParam.put("lastName", realNameAuth.getLastName());
//                smsParam.put("loanAmt", loanOrder.getLoanAmt());
//                smsParam.put("repaymentDate", loanOrder.getRepayDate());
////               CustBankCard custBankCard = getCustBindCard(appUser.getUserUuid());
//
//                RealNameAuth auth = new RealNameAuth();
//                auth.setUserId(appUser.getUserUuid());
//                auth.setState(Constants.BIZ_STATUS_1);
//                List<RealNameAuth> realNameAuthList = realNameAuthService.selectRealNameAuthList(auth);
//
//                if (realNameAuthList.size() > 0) {
//                    BankCode bankList = new BankCode();
//                    bankList.setPaystackBankCode(realNameAuthList.get(0).getBankCode());
//                    bankList.setState(UserConstants.BUSINESS_NORMAL);
//                    List<BankCode> bankCodes = bankCodeService.selectBankCodeList(bankList);
//                    if (bankCodes.size() > 0) {
//                        smsParam.put("bankName", bankCodes.get(0).getPaystackBankName());
//                    }
//                }
//
//                smsParam.put("cardLast4", DesensitizeUtils.desensitize(loanOrder.getAccountNumber(), 3, 4));
//                break;
//            case Constants.SMS_TYPE_LOAN_FAILED:
//            case Constants.SMS_TYPE_BALANCE_INSUFFICIENT:
//                // Dear #lastName#, so sorry to inform you that your loan has failed.
//                smsParam.put("lastName", realNameAuth.getLastName());
//                break;
//            default:
//                break;
//        }
//        SmsSendData smsData = SmsSendData.builder().noticeType(Constants.SMS_NOTICE_TYPE_NOTICE).smsType(smsType).phoneNumber(appUser.getPhone()).countryCode(appUser.getCountryCode()).smsParam(smsParam).build();
//        smsService.sendSms(smsData);
//    }
//
//    private CustBankCard getCustBindCard(String userId) {
//        CustBankCard custBankCard = new CustBankCard();
//        custBankCard.setUserId(userId);
//        custBankCard.setIsDefault("Y");
//        custBankCard.setState(Constants.BIZ_STATUS_1);
//        List<CustBankCard> custBankCards = custBankCardService.selectCustBankCardList(custBankCard);
//        if (CollectionUtils.isEmpty(custBankCards)) {
//            throw new BusinessException(RspEnmu.BIND_BANK_NO_FOUND);
//        }
//        return custBankCards.get(0);
//    }
//
//    private boolean isReInitiatePay() {
//        return Integer.valueOf(sysDictDataService.selectDictLabel("biz_switch", "is_reinitiate_pay")) == 1;
//    }
//
//    public JSONObject verifyTransfer(String payTransSerialNo) {
//        JSONObject transferRes = externalApiService.invokePayStackApi("Verify-Transfer", payStackConfig.getVerifyTransfer().replace("REFERENCE", payTransSerialNo), "GET", null, null);
//        return transferRes;
//    }
//
//    private ProductInfo getProductInfo(String productCode) {
//        ProductInfo product = new ProductInfo();
//        product.setProductCode(productCode);
//        product.setState(Constants.BIZ_STATUS_0);
//        List<ProductInfo> productInfoList = productInfoService.selectProductInfoList(product);
//        if (CollectionUtils.isEmpty(productInfoList)) {
//            throw new BusinessException(RspEnmu.PRODUCT_NOT_EXISTS);
//        }
//
//        return productInfoList.get(0);
//    }
//
//    private LoanOrder generateLoanOrder(LoanReq loanReq, ProductInfo product, String custNo) {
//        LoanOrder loanOrder = new LoanOrder();
//        loanOrder.setCustNo(custNo);
//        loanOrder.setAccountNumber(loanReq.getAccountNumber());
//        loanOrder.setProductCode(loanReq.getProductCode());
//        loanOrder.setLoanAmt(loanReq.getLoanAmt());
//        loanOrder.setDateLateFee(product.getDateLateFee());
//        loanOrder.setLoanPurpose(loanReq.getLoanPurpose());
//        loanOrder.setLoanPurposeOther(loanReq.getLoanPurposeOther());
//        loanOrder.setLoanSerialNo(loanReq.getLoanSerialNo());
//        loanOrder.setLoanStatus(Constants.LOAN_STATUS_9_APPROVALING);
//        loanOrder.setRepayDate(DateUtils.getFewDay(product.getPeriodNum()));
//
//        BigDecimal serviceFee = loanReq.getLoanAmt().multiply(product.getServiceFee());
//        loanOrder.setServiceFee(serviceFee);
//        loanOrder.setServiceFeeRate(product.getServiceFee());
//        loanOrder.setLateFeeMaxDays(product.getLateFeeMaxDays());
//
//        loanOrder.setFkProductId(product.getId());
//        loanOrder.setInterestRate(product.getInterestRate());
//        loanOrder.setMaxQuota(product.getMaxQuota());
//        loanOrder.setMinQuota(product.getMinQuota());
//        loanOrder.setIsSinglePayment(product.getIsSinglePayment());
//        loanOrder.setLateFeeGracePeriod(product.getLateFeeGracePeriod());
//        loanOrder.setPeriodNum(product.getPeriodNum());
//        loanOrder.setProductName(product.getProductName());
//        loanOrder.setUnit(product.getUnit());
//
//        BigDecimal interestAmt = loanReq.getLoanAmt().multiply(product.getInterestRate()).multiply(BigDecimal.valueOf(product.getPeriodNum()));
//        loanOrder.setInterestAmt(interestAmt);
//
//        loanOrder.setTotalAmt(loanReq.getLoanAmt().add(interestAmt).add(serviceFee));
//
//        loanOrderService.insertLoanOrder(loanOrder);
//        return loanOrder;
//    }
//
//    private void checkPayAccountBalance(Long loanOrderId, CreditAccount creditAccount, BigDecimal loanAmt, AppUser appUser) {
//        LoanOrder loanOrder = new LoanOrder();
//        loanOrder.setId(loanOrderId);
//        loanOrder.setLoanAmt(loanAmt);
//        loanOrder.setCustNo(creditAccount.getCustNo());
//
//        if (payTransService.isPayAccountBalanceSufficient(loanAmt)) {
//            updateFrozenAndLoanStatus(loanOrder, creditAccount.getId(), Constants.LOAN_STATUS_2_INSUFFICIENT_ACCOUNT_BALANCE, RspEnmu.INSUFFICIENT_ACCOUNT_BALANCE.getRetMsg());
//            sendNotice(appUser, null, Constants.SMS_TYPE_BALANCE_INSUFFICIENT);
//            throw new BusinessException(RspEnmu.INSUFFICIENT_ACCOUNT_BALANCE);
//        }
//    }
//
//    @Override
//    public void updateFrozenAndLoanStatus(LoanOrder loanOrder, Long creditAccountId, Integer loanStatus, String errMsg) {
//        Long loanOrderId = loanOrder.getId();
//        String custNo = loanOrder.getCustNo();
//        BigDecimal loanAmt = loanOrder.getLoanAmt();
//        String freezeDate = loanOrder.getFreezeDate();
//
//        CreditAccount account = creditAccountService.selectCreditAccountById(creditAccountId);
//        BigDecimal frozenQuota = account.getFrozenQuota();
//
//        LoanOrder order = new LoanOrder();
//        order.setId(loanOrderId);
//        order.setLoanStatus(loanStatus);
//        order.setFreezeDate(freezeDate);
//        if (StringUtils.isNotBlank(errMsg)) {
//            order.setRemark(errMsg);
//        }
//        if (Func.isNotEmpty(loanOrder.getContractNo())) {
//            order.setContractNo(loanOrder.getContractNo());
//        }
//        loanOrderService.updateLoanOrder(order);
//
//        //锁住客户账户再操作
//        String lockKey = Constants.CUST_ACCOUNT_LOCK_KEY_PREFIX + custNo;
//
//        int j = 0;//重试次数
//        while (j < Constants.CUST_ACCOUNT_LOCK_REGET_COUNT) {//重试次数内
//            j++;
//            log.info("Repayment 客户号 {} 第 {} 次获取账户锁", custNo, j);
//            String lockValue = IdUtils.fastSimpleUUID();
//            boolean lock = redisCache.lock(lockKey, lockValue);//获取锁
//
//            if (lock) {
//                try {
//                    long start = System.currentTimeMillis();
//                    CreditAccount cacc = new CreditAccount();
//                    cacc.setId(creditAccountId);
//                    cacc.setFrozenQuota(frozenQuota.subtract(loanAmt).doubleValue() <= 0 ? BigDecimal.ZERO : frozenQuota.subtract(loanAmt));
////        cacc.setFrozenQuota(loanAmt.multiply(new BigDecimal(-1)));
//
//                    if (loanStatus.equals(Constants.LOAN_STATUS_4_LOAN_SUCCESS)) {
//                        // cacc.setLoanQuota(loanAmt);
//                        // cacc.setLoanPrincipal(loanAmt);
//                    }
//
//                    creditAccountService.updateCreditAccount(cacc);
//                    // loanMapper.updatefrozenQuota(cacc);
//                    //无需重试
//                    long end = System.currentTimeMillis();
//                    log.info("锁占用时间，耗时：" + (end - start) + " ms");
//                    break;
//                } finally {
//                    //释放锁
//                    redisCache.unLock(lockKey, lockValue);
//                }
//            } else {
//                log.info("Repayment 客户号 {} 第 {} 次获取账户锁失败", custNo, j);
//
//                try {
//                    Thread.sleep(Constants.CUST_ACCOUNT_LOCK_SLEEP_TIME);
//                } catch (InterruptedException e) {
//                    log.error("Repayment 线程 sleep 异常", e);
//                }
//            }
//        }
//    }
//
//    @Override
//    public List<RaiseLimitTaskVo> getCustNotSettledIou0_3() {
//        return loanMapper.getCustNotSettledIou0_3();
//    }
//
//    @Override
//    public String againTrigger(LoanOrder loanOrder) {
//        //前置校验
//        CreditFlag creditFlagQuery = new CreditFlag();
//        creditFlagQuery.setSerialNo(loanOrder.getLoanSerialNo());
//        creditFlagQuery.setType(com.ruoyi.common.constant.Constants.RULE_TYPE_LOAN);
//        List<CreditFlag> creditFlags = creditFlagService.selectCreditFlagList(creditFlagQuery);
//
//        String phone = "";
//        String lastName = "";
//        String fullName = "";
//
//        QueryWrapper<RealNameAuth> realNameAuthQueryWrapper = new QueryWrapper<>();
//        realNameAuthQueryWrapper.eq("cust_no", loanOrder.getCustNo()).select("first_name", "middle_name", "last_name", "user_id");
//        RealNameAuth realNameAuth = iRealNameAuthService.getOne(realNameAuthQueryWrapper);
//
//        if (realNameAuth != null) {
//            fullName = realNameAuth.getFullName();
//            lastName = realNameAuth.getLastName();
//
//            //查询用户手机号user_uuid
//            QueryWrapper<AppUser> appUserQueryWrapper = new QueryWrapper<>();
//            appUserQueryWrapper.eq("user_uuid", realNameAuth.getUserId()).select("phone");
//            AppUser appUser = iAppUserService.getOne(appUserQueryWrapper);
//            phone = appUser.getPhone();
//        }
//
//        if (creditFlags.size() == 0) {
//            return "false";
//        }
//
//        if (Func.hasEmpty(creditFlags.get(0).getOrderFlag(), creditFlags.get(0).getDeviceFlag(), creditFlags.get(0).getAppsFlag(), creditFlags.get(0).getContactsFlag())) {
//
//            CreditFlag creditFlag = creditFlags.get(0);
//
//            if (Func.hasEmpty(creditFlag.getAppsFlag(), creditFlag.getContactsFlag())) {
//                log.info("为空-----AppsFlag:{};ContactsFlag:{}", creditFlag.getAppsFlag(), creditFlag.getContactsFlag());
//                RulePremiseVo rulePremiseVo = new RulePremiseVo().builder().custNo(loanOrder.getCustNo()).serialNo(loanOrder.getLoanSerialNo()).type("loan").build();
//                creditFlag = rulePremiseService.flagProcess(rulePremiseVo, creditFlag);
//                String deviceIdByUserId = appDeviceInfoService.getDeviceIdByUserId(realNameAuth.getUserId(), creditFlag.getCreateTime());
//                creditFlag = rulePremiseService.flagProcessV228(deviceIdByUserId, realNameAuth.getUserId(), creditFlag);
//                if (!Func.hasEmpty(creditFlag.getAppsFlag(), creditFlag.getContactsFlag())) {
//                    log.info("修改-----AppsFlag:{};ContactsFlag:{}", creditFlag.getAppsFlag(), creditFlag.getContactsFlag());
//                    iCreditFlagService.updateCreditFlag(creditFlag);
//                }
//            }
//
//            if (Func.hasEmpty(creditFlag.getOrderFlag(), creditFlag.getDeviceFlag(), creditFlag.getAppsFlag(), creditFlag.getContactsFlag())) {
//
//                CreditAccount creditAccount = getCreditAccount(loanOrder.getCustNo());
//                this.updateFrozenAndLoanStatus(loanOrder, creditAccount.getId(), LOAN_STATUS_1o_CANCEL, "CreditFlag has Empty");
//
//                //发送邮件
//                customerAndonService.sendAndonEamil(creditFlags.get(0), phone, fullName);
//
//                //触发短信
//                JSONObject smsParam = new JSONObject();
//                smsParam.put("lastName", lastName);
//                smsParam.put("amount", loanOrder.getLoanAmt());
//
//                SmsSendData smsData = SmsSendData.builder().noticeType(Constants.SMS_NOTICE_TYPE_NOTICE).smsType(Constants.ANDON_LOAN).phoneNumber(phone).countryCode("+234").smsParam(smsParam).build();
//                asyncService.sendSms(smsData);
//
//                //更改用户标签
//                asyncService.apdUserTag(AppUserMark.builder().userId(realNameAuth.getUserId()).build(), UserTagEnum.LOAN_FAILED);
//
//                return "false";
//            }
//        }
//
//        String error = "";
//        try {
//            this.rulePass(loanOrder.getLoanSerialNo());
//            //重新查询
//            QueryWrapper<LoanOrder> loanOrderQueryWrapper = new QueryWrapper<>();
//            loanOrderQueryWrapper.eq("loan_serial_no", loanOrder.getLoanSerialNo());
//            loanOrder = loanOrderService.getOne(loanOrderQueryWrapper);
//
//        } catch (Exception e) {
//            log.error("提现卡单处理异常-流水号:{}", loanOrder.getLoanSerialNo(), e);
//            error = e.getMessage();
//        } finally {
//            if (loanOrder.getLoanStatus() == Constants.LOAN_STATUS_9_APPROVALING) {
//                JSONObject andonContent = customerAndonService.getAndonContent(creditFlags.get(0), phone, fullName);
//                //触发飞书提醒
//                customerAndonService.sendAndonFeishu(creditFlags.get(0).getType(), andonContent);
//                //触发邮件
//                customerAndonService.sendAndonEamil(creditFlags.get(0).getType(), andonContent);
//                return error;
//            } else {
//                return "true";
//            }
//        }
//    }
//
//    private boolean isLoanApplyOnTheWay(String custNo) {
//        List<LoanOrder> loanOrders = loanMapper.loanApplyOnTheWay(custNo);
//        if (CollectionUtils.isEmpty(loanOrders)) {
//            return false;
//        }
//        return true;
//    }
//}
